package 双向链表;

import java.util.List;

public class MyLinkedList implements IList{
    //因为是双向链表,所以至少有三个域
    static class ListNode{
        public int val;
        public ListNode next;
        public ListNode prev;
        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode head;//头
    public ListNode last;//尾
    @Override
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        if(head==null){
            head = node;
            last = node;
        }else{
            node.next = head;
            head.prev = node;
            head=node;
        }
    }

    @Override
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if(head==null){
            head=node;
            last=node;
        }else{
            node.prev = last;
            last.next = node;
            last = node;
        }
    }

    @Override
    public void addIndex(int index, int data) throws IndexException,NullException{
        ListNode node = new ListNode(data);
        if(index<0||index>size()){
            throw new IndexException("警告:index不合法!");
        }
        if(head==null){
            head=node;
            last = node;
            return;
        }
        if(index==0){
            addFirst(data);
            return;
        }
        if (index==size()){
            addLast(data);
            return;
        }
        ListNode cur = searchCur(index);
        node.next = cur;
        cur.prev.next = node;
        node.prev = cur.prev;
        cur.prev=node;
    }

    public ListNode searchCur(int index){
        int count= 0;
        ListNode cur = head;
        while (count!=index){
            cur = cur.next;
            count++;
        }
        return cur;
    }

    @Override
    public boolean contains(int key) {
        ListNode cur = head;
        while (cur!=null){
            if (cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {

    }

    @Override
    public void removeAllKey() {

    }

    @Override
    public int size() {
        int count=0;
        ListNode cur = head;
        while(cur!=null){
            count++;
            cur = cur.next;
        }
        return count;
    }

    @Override
    public void display() throws NullException{
        if(head==null){
            throw new NullException("警告:链表为空!");
        }
        ListNode cur = head;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }

    @Override
    public void clear() {
        head=null;
        last = null;
    }
}
